package com.homson.servicedomain.domain.account;

import com.homson.coreservice.servicecommon.co.AccountCreateCO;
import com.homson.coreservice.servicecommon.enumeration.AccountTypeEnum;
import com.homson.coreservice.servicecommon.expection.BizException;
import com.homson.coreservice.servicecommon.expection.SystemException;
import com.homson.coreservice.servicecommon.utils.IDWorkerUtils;
import com.homson.servicedomain.domain.user.UserQueryCommand;
import com.homson.coreservice.serviceinfrastructure.datasource.repository.account.AccountRepository;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @author: homson_leo
 * @contact: hey_超级巨星（Homson_Leo）- 刘泓岑 1196816884@qq.com
 * @time: 2025/10/19 12:29 PM
 **/
@Service
@Slf4j
public class AccountCreateCommand {
    
    @Resource
    private UserQueryCommand userQueryCommand;
    
    @Resource
    private AccountRepository accountRepository;
    
    public void createAccount(Long userId, AccountCreateCO cmd) throws Exception {
        try{
            if(!userQueryCommand.isUserExist(userId)){
                throw new BizException("用户不存在");
            }
            AccountTypeEnum accountType = AccountTypeEnum.of(cmd.getAccountType());
            if(Objects.isNull(accountType)){
                throw new SystemException("不存在的账户类型");
            }
            Boolean accountExist = accountRepository.isAccountExist(accountType, cmd.getAccountName());
            if(accountExist){
                throw new BizException("已存在同名账户，请换一个名字");
            }
            Long accountId = IDWorkerUtils.generateSnowId();
            accountRepository.createAccount(accountId, cmd);
        }catch (Exception e){
            log.error(AccountCreateCommand.class.getSimpleName(), e);
            throw new SystemException(e.getMessage());
        }
    }

}
